#!/bin/sh

SCRIPT_TAG="initapk"

# 网络检测函数
check_network() {
    logger -t "$SCRIPT_TAG" -p user.info "正在检测网络连接..."
    if ! ping -c 3 -W 3 8.8.8.8 >/dev/null 2>&1; then
        logger -t "$SCRIPT_TAG" -p user.err "网络连接检测失败"
        exit 1
    fi
}

# 带日志记录的命令执行
run_cmd() {
    local cmd="$1"
    local desc="$2"
    
    logger -t "$SCRIPT_TAG" -p user.info "开始执行: $desc"
    output=$(eval "$cmd" 2>&1)
    local exit_code=$?
    
    echo "$output" | logger -t "$SCRIPT_TAG" -p user.info
    [ $exit_code -ne 0 ] && logger -t "$SCRIPT_TAG" -p user.err "操作失败: $desc (code:$exit_code)"
    
    return $exit_code
}

###########################
# 主程序流程
###########################

# 网络连通性检测
check_network

# 更新软件源
run_cmd "apk update" "更新软件源" || exit 1

# 软件包安装逻辑
if [ -f "/etc/backup/installed_packages.txt" ]; then
    pkgs=$(cat /etc/backup/installed_packages.txt | tr '\n' ' ')
    run_cmd "apk add $pkgs" "批量安装软件包" || exit 2
else
    run_cmd "apk add docker-compose \
        luci-i18n-samba4-zh-cn \
        luci-i18n-upnp-zh-cn \
        luci-i18n-usb3disable-zh-cn" "默认软件包安装" || exit 3
fi

logger -t "$SCRIPT_TAG" -p user.info "所有操作已完成"